<template>
  <div style="display: flex; justify-content: center; align-items: center">
    <el-form
      ref="FormData"
      :model="FormData"
      label-width="80px"
      class="demo-ruleForm"
      style="width: 50%"
      label-position="left"
      :rules="rules"
    >
      <el-form-item label="用户名" prop="name">
        <el-input v-model="FormData.name" type="text">
          <template #suffix v-if="FormData.name != null && FormData.name != ''">
            <template v-if="userIsExist">
              <el-tooltip content="当前用户名可以使用" placement="right">
                <el-icon class="el-input__icon" color="green" :size="20"
                  ><circle-check-filled
                /></el-icon>
              </el-tooltip>
            </template>
            <template v-if="!userIsExist">
              <el-tooltip content="当前用户名已被注册" placement="right">
                <el-icon class="el-input__icon" color="red" :size="20"
                  ><circle-close-filled
                /></el-icon>
              </el-tooltip>
            </template>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="FormData.password" type="password"></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="passwordAgain">
        <el-input v-model="FormData.passwordAgain" type="password"></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="phoneNum">
        <el-input v-model="FormData.phoneNum" type="text"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="FormData.email" type="text"></el-input>
      </el-form-item>
      <el-form-item label="所属单位" prop="unit">
        <el-input v-model="FormData.unit" type="text"></el-input>
      </el-form-item>
      <el-form-item label="用户组" prop="userGroupId">
        <el-select v-model="FormData.userGroupId" style="width: 100%">
          <el-option
            v-for="item in userGroupData"
            :key="item.id"
            :label="item.userGroup"
            :value="item.id"
          ></el-option>
          <el-option>
            <span
              ><router-link to="/userMessage/userGroupAdd"
                >添加用户组</router-link
              ></span
            >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >提交</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import axios from "../../utils/request";
import { ElNotification } from "element-plus";
import utilFunc from "../../utils/checkFuncs";
import { CircleCheckFilled, CircleCloseFilled } from "@element-plus/icons-vue";
export default {
  name: "userInfoAdd",
  components: { CircleCloseFilled, CircleCheckFilled },
  data() {
    return {
      FormData: {
        name: "",
        password: "",
        passwordAgain: "",
        phoneNum: "",
        email: "",
        unit: "",
        userGroupId: "",
      },
      userIsExist: false,
      rules: {
        name: [
          { required: true, message: "用户名不允许为空", trigger: "blur" },
        ],
        password: [
          { required: true, message: "密码不允许为空", trigger: "blur" },
        ],
        passwordAgain: [
          {
            required: true,
            validator: this.checkPasswordAgain,
            trigger: "blur",
          },
        ],
        phoneNum: [
          {
            required: true,
            validator: this.checkPhoneNum,
            trigger: "blur",
          },
        ],
        email: [
          {
            required: true,
            validator: this.checkEmail,
            trigger: "blur",
          },
        ],
        unit: [
          { required: true, message: "所属单位不允许为空", trigger: "blur" },
        ],
        userGroupId: [
          { required: true, message: "用户组不允许为空", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    submitForm(val) {
      if(! this.userIsExist){
        return false;
      }
      this.$refs.FormData.validate((valid) => {
        if (valid) {
          axios
            .post("/UserInfo/add", this.FormData)
            .then((res) => {
              // console.log(res.data);
              ElNotification.success(res.data.message);
              this.$router.push({ name: "sys:userInfo:list" });
            })
            .catch((err) => {
              console.log(err);
              ElNotification.error("添加失败、请稍后再试");
            });
        } else {
          return false;
        }
      });
    },
    /**
     * 检查用户名是否可用
     */
    theUserNameIsExist(userName) {
      let _this = this;
      axios
        .get("/theUserIsExit", { params: { userName: userName } })
        .then((res) => {
          if (res.data.status == 200) {
            _this.userIsExist = true;
          } else {
            _this.userIsExist = false;
          }
        });
    },
    /**
     * 表单数据校验函数
     */
    checkPasswordAgain(rule, value, callback) {
      if (value == null || value == "") {
        callback(new Error("密码不允许为空"));
      } else if (value != this.FormData.password) {
        callback(new Error("两次密码不一致"));
      } else {
        callback();
      }
    },
    checkPhoneNum(rule, value, callback) {
      if (value == null || value == "") {
        callback(new Error("电话号码不允许为空"));
      } else if (!utilFunc.thePhoneIsTure(value)) {
        callback(new Error("请输入正确的电话号码"));
      } else {
        callback();
      }
    },
    checkEmail(rule, value, callback) {
      if (value == null || value == "") {
        callback(new Error("邮箱地址不允许为空"));
      } else if (!utilFunc.theEmailIsTrue(value)) {
        callback(new Error("请输入正确的邮箱地址"));
      } else {
        callback();
      }
    },
  },
  mounted() {
    //获取用户组信息
    axios.get("/UserGroup/UserGroupInfo").then((res) => {
      if (res.data.status === 200) {
        this.userGroupData = res.data.data.userGroup;
      }
    });
  },
  watch: {
    'FormData.name'(){
        //调用后台接口验证用户名合法性
        this.theUserNameIsExist(this.FormData.name);
    },
  },
  FormData: {
    eleDateNew() {
      return JSON.parse(JSON.stringify(this.FormData));
    },
  },
};
</script>
